import java.util.PriorityQueue;

class MyTimerTask2 implements Comparable<MyTimerTask2>{
    public Runnable runnable;
    public long time;
    public MyTimerTask2(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time-o.time);
    }
}
class MyTimer2 {
    PriorityQueue<MyTimerTask2> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public MyTimer2(){
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
//                    continue;
                            locker.wait();
                        }
                        MyTimerTask2 current = queue.peek();
                        if (System.currentTimeMillis() >= current.getTime()) {
                            current.run();
                            queue.poll();
                        } else {
//                        continue;
                            locker.wait(current.getTime() - System.currentTimeMillis());
                        }

                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
}
    public void schedule(Runnable runnable ,long delay){
        synchronized (locker){
            MyTimerTask2 myTimerTask2=new MyTimerTask2(runnable, delay);
            queue.offer(myTimerTask2);
            locker.notify();
        }

    }

}

public class Demo31_MyTimer2 {
    public static void main(String[] args) {
        MyTimer2 myTimer2=new MyTimer2();
        myTimer2.schedule(()->{
            System.out.println("hello3");
        },3000);
        myTimer2.schedule(()->{
            System.out.println("hello2");
        },2000);
        myTimer2.schedule(()->{
            System.out.println("hello1");
        },1000);
        System.out.println("程序开始执行");
    }
}
